<template>
  <div class="app-container">
    <!-- 页面标题和统计信息 -->
    <div class="page-header" data-aos="fade-down">
      <div class="page-title">
        <i class="el-icon-s-marketing"></i>
        <span>雷达传感器数据管理</span>
      </div>
      <div class="page-description">
        实时监控和管理所有雷达传感器数据，确保环境安全监测系统正常运行
      </div>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-cards" data-aos="fade-up" data-aos-delay="100">
      <el-col :xs="24" :sm="12" :md="6">
        <div class="stats-card radar-card">
          <div class="stats-icon pulse-animation">
            <i class="el-icon-s-marketing"></i>
          </div>
          <div class="stats-content">
            <div class="stats-title">总检测事件</div>
            <div class="stats-value">{{ totalEvents }}</div>
            <div class="stats-trend">
              <span class="trend-text">较昨日</span>
              <span class="trend-value up">+12.5%</span>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <div class="stats-card motion-card">
          <div class="stats-icon pulse-animation">
            <i class="el-icon-warning"></i>
          </div>
          <div class="stats-content">
            <div class="stats-title">运动检测</div>
            <div class="stats-value">{{ motionEvents }}</div>
            <div class="stats-trend">
              <span class="trend-text">占比</span>
              <span class="trend-value">{{ motionPercentage }}%</span>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <div class="stats-card static-card">
          <div class="stats-icon pulse-animation">
            <i class="el-icon-success"></i>
          </div>
          <div class="stats-content">
            <div class="stats-title">静止状态</div>
            <div class="stats-value">{{ staticEvents }}</div>
            <div class="stats-trend">
              <span class="trend-text">占比</span>
              <span class="trend-value">{{ staticPercentage }}%</span>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <div class="stats-card abnormal-card">
          <div class="stats-icon pulse-animation">
            <i class="el-icon-warning-outline"></i>
          </div>
          <div class="stats-content">
            <div class="stats-title">异常事件</div>
            <div class="stats-value">{{ abnormalEvents }}</div>
            <div class="stats-trend">
              <span class="trend-text">占比</span>
              <span class="trend-value">{{ abnormalPercentage }}%</span>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 雷达数据趋势图表 -->
    <el-card class="chart-card" shadow="hover" data-aos="fade-up" data-aos-delay="200">
      <div slot="header" class="card-header">
        <span><i class="el-icon-s-marketing"></i> 雷达数据趋势分析</span>
        <div class="chart-controls">
          <el-switch
            v-model="realTimeUpdate"
            active-text="实时更新"
            inactive-text="手动刷新"
            @change="handleRealTimeToggle"
          ></el-switch>
          <el-radio-group v-model="chartTimeRange" size="small">
            <el-radio-button label="1h">1小时</el-radio-button>
            <el-radio-button label="6h">6小时</el-radio-button>
            <el-radio-button label="1d">1天</el-radio-button>
            <el-radio-button label="7d">7天</el-radio-button>
          </el-radio-group>
        </div>
      </div>
      <div class="chart-container" ref="radarChart"></div>
    </el-card>

    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="hover" data-aos="fade-up" data-aos-delay="300">
      <div slot="header" class="card-header">
        <span><i class="el-icon-search"></i> 数据筛选</span>
        <el-button type="text" @click="showSearch = !showSearch">
          {{ showSearch ? '收起' : '展开' }}
          <i :class="showSearch ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i>
        </el-button>
      </div>
      <el-collapse-transition>
        <div v-show="showSearch">
          <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="100px">
            <el-form-item label="关联设备ID" prop="deviceId">
              <el-input
                v-model="queryParams.deviceId"
                placeholder="请输入关联设备ID"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="事件类型" prop="eventType">
              <el-select v-model="queryParams.eventType" placeholder="请选择事件类型" clearable>
                <el-option label="运动检测" value="motion"></el-option>
                <el-option label="静止状态" value="static"></el-option>
                <el-option label="接近检测" value="proximity"></el-option>
                <el-option label="存在检测" value="presence"></el-option>
                <el-option label="异常事件" value="abnormal"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="事件值" prop="value">
              <el-input
                v-model="queryParams.value"
                placeholder="请输入事件值"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="数据采集时间">
              <el-date-picker
                v-model="daterangeRecordTime"
                style="width: 240px"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="入库时间">
              <el-date-picker
                v-model="daterangeCreateTime"
                style="width: 240px"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              ></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-collapse-transition>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="table-card" shadow="hover" data-aos="fade-up" data-aos-delay="300">
      <div slot="header" class="card-header">
        <span><i class="el-icon-s-marketing"></i> 雷达传感器数据</span>
        <div class="card-operations">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="small"
            @click="handleAdd"
            v-hasPermi="['system:radarSensor:add']"
          >新增数据</el-button>
          <el-button
            type="success"
            icon="el-icon-edit"
            size="small"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:radarSensor:edit']"
          >批量修改</el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="small"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:radarSensor:remove']"
          >批量删除</el-button>
          <el-button
            type="warning"
            icon="el-icon-download"
            size="small"
            @click="handleExport"
            v-hasPermi="['system:radarSensor:export']"
          >导出数据</el-button>
          <el-button
            type="info"
            icon="el-icon-data-analysis"
            size="small"
            @click="handleDataAnalysis"
            v-hasPermi="['system:radarSensor:analysis']"
          >数据分析</el-button>
        </div>
      </div>

      <!-- 数据表格 -->
      <el-table 
        v-loading="loading" 
        :data="radarSensorList" 
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
        :header-cell-style="{background:'#f5f7fa',color:'#606266'}"
        :cell-style="{padding: '8px 0'}"
        border
        stripe
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="记录ID" align="center" prop="id" width="80" sortable="custom" />
        <el-table-column label="设备ID" align="center" prop="deviceId" width="120" sortable="custom">
          <template slot-scope="scope">
            <div class="device-id">
              <i class="el-icon-monitor"></i>
              <el-link type="primary" @click="viewDeviceDetails(scope.row.deviceId)">{{ scope.row.deviceId }}</el-link>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="事件类型" align="center" prop="eventType" width="120" sortable="custom">
          <template slot-scope="scope">
            <div class="event-type">
              <el-tag :type="getEventTypeTag(scope.row.eventType)" class="event-tag">
                <i :class="getEventTypeIcon(scope.row.eventType)"></i>
                {{ getEventTypeText(scope.row.eventType) }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="事件值" align="center" prop="value" width="120" sortable="custom">
          <template slot-scope="scope">
            <div class="event-value">
              <el-progress 
                :percentage="getEventPercentage(scope.row.value)" 
                :status="getEventStatus(scope.row.eventType)"
                :stroke-width="8"
                :show-text="false"
              ></el-progress>
              <span class="value-text">{{ scope.row.value }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="原始数据" align="center" prop="rawData" width="150">
          <template slot-scope="scope">
            <el-tooltip :content="scope.row.rawData" placement="top" :disabled="!scope.row.rawData || scope.row.rawData.length < 15">
              <span class="raw-data">{{ scope.row.rawData ? (scope.row.rawData.length > 15 ? scope.row.rawData.substring(0, 15) + '...' : scope.row.rawData) : '无' }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="采集时间" align="center" prop="recordTime" width="180" sortable="custom">
          <template slot-scope="scope">
            <div class="time-display">
              <div class="date">{{ parseTime(scope.row.recordTime, '{y}-{m}-{d}') }}</div>
              <div class="time">{{ parseTime(scope.row.recordTime, '{h}:{i}:{s}') }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="入库时间" align="center" prop="createTime" width="180" sortable="custom">
          <template slot-scope="scope">
            <div class="time-display">
              <div class="date">{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</div>
              <div class="time">{{ parseTime(scope.row.createTime, '{h}:{i}:{s}') }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180" fixed="right">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              class="action-btn view-btn"
              @click="handleView(scope.row)"
            >详情</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              class="action-btn edit-btn"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:radarSensor:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              class="action-btn delete-btn"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:radarSensor:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改雷达传感器数据对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="关联设备ID" prop="deviceId">
          <el-input v-model="form.deviceId" placeholder="请输入关联设备ID" />
        </el-form-item>
        <el-form-item label="事件类型" prop="eventType">
          <el-select v-model="form.eventType" placeholder="请选择事件类型" style="width: 100%">
            <el-option label="运动检测" value="motion"></el-option>
            <el-option label="静止状态" value="static"></el-option>
            <el-option label="接近检测" value="proximity"></el-option>
            <el-option label="存在检测" value="presence"></el-option>
            <el-option label="异常事件" value="abnormal"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="事件值" prop="value">
          <el-input-number v-model="form.value" :min="0" :max="100" style="width: 100%"></el-input-number>
        </el-form-item>
        <el-form-item label="原始数据" prop="rawData">
          <el-input 
            v-model="form.rawData" 
            type="textarea" 
            :rows="3"
            placeholder="请输入原始数据（可选）">
          </el-input>
        </el-form-item>
        <el-form-item label="数据采集时间" prop="recordTime">
          <el-date-picker
            v-model="form.recordTime"
            type="datetime"
            placeholder="选择数据采集时间"
            style="width: 100%"
            value-format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 数据详情对话框 -->
    <el-dialog title="雷达传感器数据详情" :visible.sync="detailOpen" width="600px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="记录ID">{{ currentRow.id }}</el-descriptions-item>
        <el-descriptions-item label="设备ID">{{ currentRow.deviceId }}</el-descriptions-item>
        <el-descriptions-item label="事件类型">
          <el-tag :type="getEventTypeTag(currentRow.eventType)">{{ getEventTypeText(currentRow.eventType) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="事件值">{{ currentRow.value }}</el-descriptions-item>
        <el-descriptions-item label="原始数据" span="2">{{ currentRow.rawData || '无' }}</el-descriptions-item>
        <el-descriptions-item label="数据采集时间">{{ parseTime(currentRow.recordTime) }}</el-descriptions-item>
        <el-descriptions-item label="入库时间">{{ parseTime(currentRow.createTime) }}</el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRadarSensor, getRadarSensor, delRadarSensor, addRadarSensor, updateRadarSensor } from "@/api/system/radarSensor"
import * as echarts from 'echarts'

export default {
  name: "RadarSensor",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 雷达传感器数据表格数据
      radarSensorList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示详情弹出层
      detailOpen: false,
      // 当前查看的行数据
      currentRow: {},
      // 图表时间范围
      chartTimeRange: '1d',
      // 图表实例
      chart: null,
      // 实时更新开关
      realTimeUpdate: false,
      // 实时更新定时器
      realTimeTimer: null,
      // 实时更新间隔（毫秒）
      realTimeInterval: 30000,
      // 原始数据时间范围
      daterangeRecordTime: [],
      // 原始数据时间范围
      daterangeCreateTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceId: null,
        eventType: null,
        value: null,
        rawData: null,
        recordTime: null,
        createTime: null,
        orderByColumn: null,
        isAsc: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        deviceId: [
          { required: true, message: "关联设备ID不能为空", trigger: "blur" }
        ],
        eventType: [
          { required: true, message: "事件类型不能为空", trigger: "change" }
        ],
        value: [
          { required: true, message: "事件值不能为空", trigger: "blur" }
        ],
        recordTime: [
          { required: true, message: "数据采集时间不能为空", trigger: "blur" }
        ]
      }
    }
  },
  computed: {
    // 计算总检测事件数
    totalEvents() {
      return this.radarSensorList ? this.radarSensorList.length : 0;
    },
    // 计算运动检测事件数
    motionEvents() {
      if (!this.radarSensorList || this.radarSensorList.length === 0) return 0;
      return this.radarSensorList.filter(item => item.eventType === 'motion').length;
    },
    // 计算静止状态事件数
    staticEvents() {
      if (!this.radarSensorList || this.radarSensorList.length === 0) return 0;
      return this.radarSensorList.filter(item => item.eventType === 'static').length;
    },
    // 计算异常事件数
    abnormalEvents() {
      if (!this.radarSensorList || this.radarSensorList.length === 0) return 0;
      return this.radarSensorList.filter(item => item.eventType === 'abnormal').length;
    },
    // 计算接近检测事件数
    proximityEvents() {
      if (!this.radarSensorList || this.radarSensorList.length === 0) return 0;
      return this.radarSensorList.filter(item => item.eventType === 'proximity').length;
    },
    // 计算存在检测事件数
    presenceEvents() {
      if (!this.radarSensorList || this.radarSensorList.length === 0) return 0;
      return this.radarSensorList.filter(item => item.eventType === 'presence').length;
    },
    // 计算运动检测事件占比
    motionPercentage() {
      if (this.totalEvents === 0) return 0;
      return Math.round((this.motionEvents / this.totalEvents) * 100);
    },
    // 计算静止状态事件占比
    staticPercentage() {
      if (this.totalEvents === 0) return 0;
      return Math.round((this.staticEvents / this.totalEvents) * 100);
    },
    // 计算异常事件占比
    abnormalPercentage() {
      if (this.totalEvents === 0) return 0;
      return Math.round((this.abnormalEvents / this.totalEvents) * 100);
    },
    // 计算接近检测事件占比
    proximityPercentage() {
      if (this.totalEvents === 0) return 0;
      return Math.round((this.proximityEvents / this.totalEvents) * 100);
    },
    // 计算存在检测事件占比
    presencePercentage() {
      if (this.totalEvents === 0) return 0;
      return Math.round((this.presenceEvents / this.totalEvents) * 100);
    }
  },
  created() {
    this.getList()
  },
  mounted() {
    // 初始化图表
    this.$nextTick(() => {
      this.initChart()
    })
    // 添加窗口大小变化监听
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    // 销毁图表实例
    if (this.chart) {
      this.chart.dispose()
      this.chart = null
    }
    // 移除窗口大小变化监听
    window.removeEventListener('resize', this.handleResize)
    // 清理实时更新定时器
    this.stopRealTimeUpdate()
  },
  methods: {
    /** 查询雷达传感器数据列表 */
    getList() {
      this.loading = true
      this.queryParams.params = {}
      if (null != this.daterangeRecordTime && '' != this.daterangeRecordTime) {
        this.queryParams.params["beginRecordTime"] = this.daterangeRecordTime[0]
        this.queryParams.params["endRecordTime"] = this.daterangeRecordTime[1]
      }
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0]
        this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1]
      }
      listRadarSensor(this.queryParams).then(response => {
        this.radarSensorList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        deviceId: null,
        eventType: null,
        value: null,
        rawData: null,
        recordTime: null,
        createTime: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeRecordTime = []
      this.daterangeCreateTime = []
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加雷达传感器数据"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getRadarSensor(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改雷达传感器数据"
      })
    },
    /** 查看详情按钮操作 */
    handleView(row) {
      this.currentRow = row
      this.detailOpen = true
    },
    /** 查看设备详情 */
    viewDeviceDetails(deviceId) {
      this.$router.push({
        path: '/system/device',
        query: { deviceId: deviceId }
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateRadarSensor(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addRadarSensor(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除雷达传感器数据编号为"' + ids + '"的数据项？').then(function() {
        return delRadarSensor(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/radarSensor/export', {
        ...this.queryParams
      }, `radarSensor_${new Date().getTime()}.xlsx`)
    },
    /** 数据分析按钮操作 */
    handleDataAnalysis() {
      this.$modal.msgLoading('正在分析数据，请稍候...');
      
      // 模拟数据分析API调用
      setTimeout(() => {
        this.$modal.closeLoading();
        
        // 显示分析结果对话框
        this.$alert(`
          <div style="text-align: left;">
            <h3>雷达传感器数据分析报告</h3>
            <p><strong>分析时间：</strong>${this.parseTime(new Date())}</p>
            <p><strong>数据范围：</strong>${this.getDateRangeText()}</p>
            <hr>
            <h4>事件类型分布</h4>
            <ul>
              <li>运动检测事件：${this.motionEvents} 次 (${this.motionPercentage}%)</li>
              <li>静止状态事件：${this.staticEvents} 次 (${this.staticPercentage}%)</li>
              <li>接近检测事件：${this.proximityEvents} 次 (${this.proximityPercentage}%)</li>
              <li>存在检测事件：${this.presenceEvents} 次 (${this.presencePercentage}%)</li>
              <li>异常事件：${this.abnormalEvents} 次 (${this.abnormalPercentage}%)</li>
            </ul>
            <h4>趋势分析</h4>
            <p>• 异常事件占比${this.abnormalPercentage > 10 ? '偏高' : '正常'}，建议${this.abnormalPercentage > 10 ? '检查设备状态' : '继续保持'}</p>
            <p>• 运动检测与静止状态比例${Math.abs(this.motionPercentage - this.staticPercentage) < 20 ? '均衡' : '失衡'}，${Math.abs(this.motionPercentage - this.staticPercentage) < 20 ? '检测区域活动正常' : '可能存在环境异常'}</p>
            <h4>建议</h4>
            <p>• ${this.abnormalPercentage > 10 ? '建议检查雷达传感器设备状态，确保设备正常运行' : '设备运行状态良好，继续保持'}</p>
            <p>• ${this.totalEvents < 100 ? '检测事件较少，可能存在检测盲区' : '检测事件数量充足，覆盖范围良好'}</p>
          </div>
        `, '数据分析结果', {
          dangerouslyUseHTMLString: true,
          customClass: 'analysis-dialog'
        });
      }, 1500);
    },
    /** 获取日期范围文本 */
    getDateRangeText() {
      if (this.daterangeRecordTime && this.daterangeRecordTime.length === 2) {
        return `${this.daterangeRecordTime[0]} 至 ${this.daterangeRecordTime[1]}`;
      }
      return '全部数据';
    },
    /** 获取事件类型标签样式 */
    getEventTypeTag(eventType) {
      switch(eventType) {
        case 'motion': return 'danger';
        case 'static': return 'success';
        case 'proximity': return 'warning';
        case 'presence': return 'primary';
        case 'abnormal': return 'danger';
        default: return 'info';
      }
    },
    /** 获取事件类型文本 */
    getEventTypeText(eventType) {
      switch(eventType) {
        case 'motion': return '运动检测';
        case 'static': return '静止状态';
        case 'proximity': return '接近检测';
        case 'presence': return '存在检测';
        case 'abnormal': return '异常事件';
        default: return eventType || '未知';
      }
    },
    /** 获取事件值百分比 */
    getEventPercentage(value) {
      // 将事件值转换为百分比，假设最大值为100
      const num = parseInt(value) || 0;
      return Math.min(num, 100);
    },
    /** 获取事件状态 */
    getEventStatus(eventType) {
      switch(eventType) {
        case 'motion': return 'exception';
        case 'static': return 'success';
        case 'proximity': return 'warning';
        case 'presence': return '';
        case 'abnormal': return 'exception';
        default: return '';
      }
    },
    /** 初始化图表 */
    initChart() {
      if (!this.$refs.radarChart) return
      
      this.chart = echarts.init(this.$refs.radarChart)
      this.updateChartData()
    },
    /** 实时更新开关处理 */
    handleRealTimeToggle(value) {
      if (value) {
        this.startRealTimeUpdate();
      } else {
        this.stopRealTimeUpdate();
      }
    },
    /** 开始实时更新 */
    startRealTimeUpdate() {
      this.stopRealTimeUpdate(); // 先停止现有的定时器
      
      this.realTimeTimer = setInterval(() => {
        this.getList(); // 获取最新数据
        this.updateChartData(); // 更新图表
        this.$notify({
          title: '数据更新',
          message: '雷达传感器数据已自动更新',
          type: 'success',
          duration: 2000
        });
      }, this.realTimeInterval);
    },
    /** 停止实时更新 */
    stopRealTimeUpdate() {
      if (this.realTimeTimer) {
        clearInterval(this.realTimeTimer);
        this.realTimeTimer = null;
      }
    },
    /** 更新图表数据 */
    updateChartData() {
      if (!this.chart) return
      
      // 根据时间范围生成模拟数据
      const timeRange = this.chartTimeRange
      let dataCount = 24 // 默认1天24小时
      let timeFormat = 'HH:mm'
      
      if (timeRange === '1h') {
        dataCount = 12 // 1小时12个数据点
        timeFormat = 'HH:mm'
      } else if (timeRange === '6h') {
        dataCount = 18 // 6小时18个数据点
        timeFormat = 'HH:mm'
      } else if (timeRange === '1d') {
        dataCount = 24 // 1天24个数据点
        timeFormat = 'HH:mm'
      } else if (timeRange === '7d') {
        dataCount = 7 // 7天7个数据点
        timeFormat = 'MM-DD'
      }
      
      // 生成时间轴
      const timeAxis = []
      const now = new Date()
      
      for (let i = dataCount - 1; i >= 0; i--) {
        const time = new Date(now)
        if (timeRange === '1h') {
          time.setMinutes(now.getMinutes() - i * 5)
        } else if (timeRange === '6h') {
          time.setMinutes(now.getMinutes() - i * 20)
        } else if (timeRange === '1d') {
          time.setHours(now.getHours() - i)
        } else if (timeRange === '7d') {
          time.setDate(now.getDate() - i)
        }
        
        timeAxis.push(this.parseTime(time, timeFormat))
      }
      
      // 生成模拟数据
      const motionData = []
      const staticData = []
      const proximityData = []
      const presenceData = []
      const abnormalData = []
      
      for (let i = 0; i < dataCount; i++) {
        motionData.push(Math.floor(Math.random() * 50) + 10)
        staticData.push(Math.floor(Math.random() * 40) + 20)
        proximityData.push(Math.floor(Math.random() * 30) + 5)
        presenceData.push(Math.floor(Math.random() * 60) + 10)
        abnormalData.push(Math.floor(Math.random() * 10))
      }
      
      // 设置图表配置
      const option = {
        title: {
          text: '雷达传感器事件类型分布',
          left: 'center',
          textStyle: {
            color: '#303133',
            fontSize: 16
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        legend: {
          data: ['运动检测', '静止状态', '接近检测', '存在检测', '异常事件'],
          top: 30
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: timeAxis
        },
        yAxis: {
          type: 'value',
          name: '事件数量'
        },
        series: [
          {
            name: '运动检测',
            type: 'line',
            stack: 'Total',
            smooth: true,
            lineStyle: {
              width: 0
            },
            showSymbol: false,
            areaStyle: {
              opacity: 0.8,
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(245, 108, 108, 0.8)' },
                { offset: 1, color: 'rgba(245, 108, 108, 0.1)' }
              ])
            },
            emphasis: {
              focus: 'series'
            },
            data: motionData
          },
          {
            name: '静止状态',
            type: 'line',
            stack: 'Total',
            smooth: true,
            lineStyle: {
              width: 0
            },
            showSymbol: false,
            areaStyle: {
              opacity: 0.8,
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(103, 194, 58, 0.8)' },
                { offset: 1, color: 'rgba(103, 194, 58, 0.1)' }
              ])
            },
            emphasis: {
              focus: 'series'
            },
            data: staticData
          },
          {
            name: '接近检测',
            type: 'line',
            stack: 'Total',
            smooth: true,
            lineStyle: {
              width: 0
            },
            showSymbol: false,
            areaStyle: {
              opacity: 0.8,
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(230, 162, 60, 0.8)' },
                { offset: 1, color: 'rgba(230, 162, 60, 0.1)' }
              ])
            },
            emphasis: {
              focus: 'series'
            },
            data: proximityData
          },
          {
            name: '存在检测',
            type: 'line',
            stack: 'Total',
            smooth: true,
            lineStyle: {
              width: 0
            },
            showSymbol: false,
            areaStyle: {
              opacity: 0.8,
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(64, 158, 255, 0.8)' },
                { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
              ])
            },
            emphasis: {
              focus: 'series'
            },
            data: presenceData
          },
          {
            name: '异常事件',
            type: 'line',
            stack: 'Total',
            smooth: true,
            lineStyle: {
              width: 0
            },
            showSymbol: false,
            areaStyle: {
              opacity: 0.8,
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(255, 99, 132, 0.8)' },
                { offset: 1, color: 'rgba(255, 99, 132, 0.1)' }
              ])
            },
            emphasis: {
              focus: 'series'
            },
            data: abnormalData
          }
        ]
      }
      
      this.chart.setOption(option)
    },
    /** 处理窗口大小变化 */
    handleResize() {
      if (this.chart) {
        this.chart.resize()
      }
    },
    /** 处理表格排序 */
    handleSortChange(column) {
      this.queryParams.orderByColumn = column.prop
      this.queryParams.isAsc = column.order === 'ascending' ? 'asc' : 'desc'
      this.getList()
    },
    /** 获取事件类型图标 */
    getEventTypeIcon(eventType) {
      switch(eventType) {
        case 'motion': return 'el-icon-warning';
        case 'static': return 'el-icon-success';
        case 'proximity': return 'el-icon-warning-outline';
        case 'presence': return 'el-icon-user';
        case 'abnormal': return 'el-icon-error';
        default: return 'el-icon-question';
      }
    }
  },
  watch: {
    chartTimeRange: {
      handler() {
        this.updateChartData()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.page-header {
  margin-bottom: 20px;
  
  .page-title {
    display: flex;
    align-items: center;
    font-size: 24px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 10px;
    
    i {
      margin-right: 10px;
      color: #409EFF;
    }
  }
  
  .page-description {
    font-size: 14px;
    color: #606266;
    line-height: 1.5;
  }
}

.stats-cards {
  margin-bottom: 20px;
  
  .stats-card {
    background: #fff;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    display: flex;
    align-items: center;
    transition: all 0.3s ease;
    
    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
    }
    
    .stats-icon {
      width: 60px;
      height: 60px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 15px;
      
      i {
        font-size: 24px;
      }
    }
    
    .stats-content {
      flex: 1;
      
      .stats-title {
        font-size: 14px;
        color: #909399;
        margin-bottom: 5px;
      }
      
      .stats-value {
        font-size: 24px;
        font-weight: 600;
        color: #303133;
      }
      
      .stats-trend {
        display: flex;
        align-items: center;
        margin-top: 5px;
        
        .trend-text {
          font-size: 12px;
          color: #909399;
          margin-right: 5px;
        }
        
        .trend-value {
          font-size: 12px;
          font-weight: 600;
          
          &.up {
            color: #67C23A;
          }
          
          &.down {
            color: #F56C6C;
          }
        }
      }
    }
    
    // 雷达卡片样式
    &.radar-card {
      .stats-icon {
        background-color: rgba(64, 158, 255, 0.1);
        color: #409EFF;
      }
    }
    
    // 运动检测卡片样式
    &.motion-card {
      .stats-icon {
        background-color: rgba(245, 108, 108, 0.1);
        color: #F56C6C;
      }
    }
    
    // 静止状态卡片样式
    &.static-card {
      .stats-icon {
        background-color: rgba(103, 194, 58, 0.1);
        color: #67C23A;
      }
    }
    
    // 异常事件卡片样式
    &.abnormal-card {
      .stats-icon {
        background-color: rgba(230, 162, 60, 0.1);
        color: #E6A23C;
      }
    }
  }
  
  // 脉冲动画效果
  .pulse-animation {
    animation: pulse 2s infinite;
  }
  
  @keyframes pulse {
    0% {
      box-shadow: 0 0 0 0 rgba(64, 158, 255, 0.4);
    }
    70% {
      box-shadow: 0 0 0 10px rgba(64, 158, 255, 0);
    }
    100% {
      box-shadow: 0 0 0 0 rgba(64, 158, 255, 0);
    }
  }
}

.search-card, .table-card {
  margin-bottom: 20px;
  border-radius: 8px;
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    span {
      font-weight: 600;
      color: #303133;
      
      i {
        margin-right: 8px;
        color: #409EFF;
      }
    }
  }
  
  .card-operations {
    display: flex;
    gap: 10px;
  }
}

.chart-card {
  margin-bottom: 20px;
  border-radius: 8px;
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    span {
      font-weight: 600;
      color: #303133;
      
      i {
        margin-right: 8px;
        color: #409EFF;
      }
    }
  }
  
  .chart-controls {
    display: flex;
    align-items: center;
    gap: 15px;
  }
  
  .chart-container {
    height: 350px;
    width: 100%;
  }
}

.el-switch {
  margin-right: 10px;
  
  .el-switch__label {
    color: #606266;
    font-size: 13px;
  }
}

.el-table {
  margin-top: 0;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  
  ::v-deep .el-table__cell {
    padding: 8px 0;
  }
  
  ::v-deep .el-table th.el-table__cell {
    padding: 12px 0;
  }
  
  ::v-deep .el-table td.el-table__cell {
    border-right: none;
  }
  
  ::v-deep .el-table--border .el-table__cell {
    border-right: none;
  }
  
  ::v-deep .el-table--group::after, 
  ::v-deep .el-table--border::after, 
  ::v-deep .el-table::before {
    background-color: transparent;
  }
  
  .device-id {
    display: flex;
    align-items: center;
    justify-content: center;
    
    i {
      margin-right: 5px;
      color: #409EFF;
    }
  }
  
  .event-type {
    .event-tag {
      display: flex;
      align-items: center;
      
      i {
        margin-right: 5px;
      }
    }
  }
  
  .event-value {
    .value-text {
      display: block;
      margin-top: 5px;
      font-size: 12px;
      color: #606266;
    }
  }
  
  .raw-data {
    font-family: monospace;
    font-size: 12px;
    color: #606266;
    background-color: #f5f7fa;
    padding: 2px 4px;
    border-radius: 3px;
  }
  
  .time-display {
    .date {
      font-size: 12px;
      color: #909399;
    }
    
    .time {
      font-size: 13px;
      color: #606266;
      font-weight: 500;
    }
  }
  
  .action-btn {
    margin: 0 2px;
    transition: all 0.2s ease;
    
    &.view-btn {
      color: #409EFF;
      
      &:hover {
        color: #66b1ff;
        transform: scale(1.1);
      }
    }
    
    &.edit-btn {
      color: #67C23A;
      
      &:hover {
        color: #85ce61;
        transform: scale(1.1);
      }
    }
    
    &.delete-btn {
      color: #F56C6C;
      
      &:hover {
        color: #f78989;
        transform: scale(1.1);
      }
    }
  }
}

.el-form-item {
  margin-bottom: 15px;
}

// 数据分析对话框样式
.analysis-dialog {
  .el-message-box {
    max-width: 600px;
    
    .el-message-box__content {
      max-height: 500px;
      overflow-y: auto;
    }
    
    h3 {
      color: #409EFF;
      margin-bottom: 15px;
      border-bottom: 2px solid #409EFF;
      padding-bottom: 8px;
    }
    
    h4 {
      color: #303133;
      margin-top: 15px;
      margin-bottom: 10px;
    }
    
    ul {
      padding-left: 20px;
      
      li {
        margin-bottom: 5px;
        line-height: 1.5;
      }
    }
    
    hr {
      border: none;
      border-top: 1px solid #EBEEF5;
      margin: 15px 0;
    }
    
    p {
      line-height: 1.6;
      margin-bottom: 8px;
    }
  }
}

.dialog-footer {
  text-align: right;
}

// 响应式布局
@media (max-width: 768px) {
  .app-container {
    padding: 10px;
  }
  
  .stats-cards {
    .el-col {
      margin-bottom: 15px;
    }
  }
  
  .card-operations {
    flex-direction: column;
    gap: 5px;
  }
}
</style>